import { ScrapeTask } from '../../shared/types'
import { logger } from '@roasmax/logger'
import { BrowserWindow } from 'electron'
import { useEntityManager } from '../storage/data-source'
import { getUserInfoSimple } from '@roasmax/weibo-scraper'
import { User } from '../storage/entities'

// Import the new modular components
import { TaskLifecycleManager } from './task-lifecycle'
import { TaskIOManager } from './task-io'
import { TaskDataManager } from './task-data'

export class TaskManager {
  private runningTasks = new Map<string, boolean>()

  // Modular components
  private lifecycleManager: TaskLifecycleManager
  private ioManager: TaskIOManager
  private dataManager: TaskDataManager

  constructor() {
    this.lifecycleManager = new TaskLifecycleManager()
    this.ioManager = new TaskIOManager()
    this.dataManager = new TaskDataManager()
  }

  /**
   * 设置主窗口引用，用于发送实时更新
   */
  setMainWindow(window: BrowserWindow) {
    this.ioManager.setMainWindow(window)
  }

  // These methods are now delegated to the modular components

  /**
   * 创建爬取任务
   */
  async createTask(taskData: Omit<ScrapeTask, 'id' | 'createdAt'>): Promise<ScrapeTask> {
    return await this.lifecycleManager.createTask(taskData)
  }

  /**
   * 停止任务
   */
  async stopTask(taskId: string): Promise<void> {
    logger.info('停止任务', { taskId })

    if (!this.runningTasks.has(taskId)) {
      throw new Error('任务未在运行中')
    }

    // 标记任务停止
    this.runningTasks.delete(taskId)

    // 更新任务状态
    this.ioManager.sendTaskStatusChange(taskId, 'failed')
    await this.lifecycleManager.updateTaskStatus(taskId, 'failed', new Date())

    logger.info('任务已停止', { taskId })
  }

  /**
   * 获取所有任务
   */
  async getAllTasks(): Promise<ScrapeTask[]> {
    return await this.lifecycleManager.getAllTasks()
  }

  /**
   * 根据ID获取任务
   */
  async getTaskById(taskId: string): Promise<ScrapeTask | null> {
    return await this.lifecycleManager.getTaskById(taskId)
  }

  /**
   * 导出任务数据
   */
  async exportTaskData(taskId: string, format: 'json' | 'csv'): Promise<string> {
    return await this.lifecycleManager.exportTaskData(taskId, format)
  }

  /**
   * 获取统计信息
   */
  async getStats(): Promise<{
    totalTasks: number
    completedTasks: number
    totalData: number
  }> {
    return await this.lifecycleManager.getStats()
  }

  /**
   * 获取微博数据统计信息
   */
  async getWeiboDataStats(): Promise<{
    total: number
    today: number
    thisWeek: number
    thisMonth: number
    totalUsers: number
    totalTasks: number
    avgInteractions: number
    topKeywords: Array<{ keyword: string; count: number }>
  }> {
    return await this.dataManager.getWeiboDataStats()
  }

  /**
   * 获取微博数据列表
   */
  async getWeiboDataList(params: {
    page: number
    pageSize: number
    keyword?: string
    filterType?: 'all' | 'original' | 'repost'
    sortBy?: 'createdAt' | 'publishedAt' | 'interactions'
    sortOrder?: 'asc' | 'desc'
  }): Promise<{
    data: any[]
    total: number
    page: number
    pageSize: number
  }> {
    return await this.dataManager.getWeiboDataList(params)
  }

  /**
   * 获取用户数据统计信息
   */
  async getUserDataStats(): Promise<{
    total: number
    today: number
    thisWeek: number
    thisMonth: number
    vipUsers: number
    verifiedUsers: number
    avgFollowers: number
    topUsers: Array<{ nickname: string; followersCount: number }>
  }> {
    return await this.dataManager.getUserDataStats()
  }

  /**
   * 获取用户数据列表
   */
  async getUserDataList(params: {
    page: number
    pageSize: number
    keyword?: string
    filterType?: 'all' | 'vip' | 'verified' | 'normal'
    sortBy?: 'createdAt' | 'followersCount' | 'statusesCount'
    sortOrder?: 'asc' | 'desc'
  }): Promise<{
    data: any[]
    total: number
    page: number
    pageSize: number
  }> {
    return await this.dataManager.getUserDataList(params)
  }

  /**
   * 调试方法：检查数据库中的用户数据
   */
  async debugUserData(): Promise<void> {
    return await this.dataManager.debugUserData()
  }

  /**
   * 批量更新用户的完整信息
   */
  async updateUsersCompleteInfo(cookies: any[], limit: number = 10): Promise<void> {
    logger.info('开始批量更新用户完整信息', { limit })

    await useEntityManager(async m => {
      const userRepo = m.getRepository(User)

      // 获取需要更新的用户（粉丝数为null的用户）
      const usersToUpdate = await userRepo
        .createQueryBuilder('user')
        .where('user.followersCount IS NULL')
        .orderBy('user.createdAt', 'DESC')
        .limit(limit)
        .getMany()

      logger.info(`找到 ${usersToUpdate.length} 个需要更新的用户`)

      for (const user of usersToUpdate) {
        try {
          logger.debug('更新用户信息', { uid: user.uid, nickname: user.nickname })

          const completeUserInfo = await this.fetchCompleteUserInfo(user.uid, cookies)

          if (completeUserInfo) {
            // 更新用户信息
            user.followersCount = completeUserInfo.followers_count || null
            user.followingCount = completeUserInfo.friends_count || null
            user.statusesCount = completeUserInfo.statuses_count || null
            user.description = completeUserInfo.description || user.description
            user.location = completeUserInfo.location || user.location
            user.verifiedType = completeUserInfo.verified_type !== undefined ? completeUserInfo.verified_type : user.verifiedType
            user.verifiedReason = completeUserInfo.verified_reason || user.verifiedReason
            user.lastUpdated = new Date()

            await userRepo.save(user)

            logger.debug('用户信息更新成功', {
              uid: user.uid,
              followersCount: user.followersCount,
              followingCount: user.followingCount,
              statusesCount: user.statusesCount
            })
          } else {
            logger.warn('无法获取用户完整信息', { uid: user.uid })
          }

          // 添加延迟避免请求过于频繁
          await new Promise(resolve => setTimeout(resolve, 2000))

        } catch (error) {
          logger.error('更新用户信息失败', { uid: user.uid, error: (error as Error).message })
        }
      }
    })

    logger.info('批量更新用户完整信息完成')
  }

  /**
   * 获取用户的完整信息
   */
  private async fetchCompleteUserInfo(uid: string, cookies: any[]): Promise<any> {
    try {
      logger.debug('获取用户完整信息', { uid })

      const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ')
      const userInfo = await getUserInfoSimple({
        uid,
        cookies: cookieString
      })

      logger.debug('获取到用户完整信息', {
        uid,
        screen_name: userInfo.screen_name,
        followers_count: userInfo.followers_count,
        friends_count: userInfo.friends_count,
        statuses_count: userInfo.statuses_count
      })

      return userInfo
    } catch (error) {
      logger.warn('获取用户完整信息失败，使用基础信息', { uid, error: (error as Error).message })
      return null
    }
  }
}
